<?php

/**
 * This is the model class for table "user".
 * and we use this class for user data control
 * @author BoyLee
 *
 *
 * The followings are the available columns in table 'user':
 * @property string $id
 * @property string $username
 * @property string $password
 * @property string $realname
 * @property string $tel
 * @property string $sex
 * @property string $class_id
 * @property integer $status_id
 */
class User extends CActiveRecord
{
  //const sex options
  const SEX_MALE = 1;
  const SEX_FEMALE = 2;
  
  
  //password repeat
  public $passwordAgain;
  //set old password for password update usage
  public $passwordOld;
  
  
	/**
	 * Returns the static model of the specified AR class.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, password', 'required'),
			array('password', 'compare', 'compareAttribute'=>'passwordAgain', 'on'=>'register, updatePass'),
			array('username', 'unique'),
			array('username', 'length', 'max'=>64, 'encoding'=>'utf-8'),
			array('password', 'length', 'max'=>32, 'encoding'=>'utf-8'),
			array('realname', 'length', 'max'=>6, 'encoding'=>'utf-8'),
			
			array('tel', 'numerical', 'integerOnly'=>true),
			array('tel', 'length', 'max'=>11),
			
			array('passwordOld', 'required', 'on'=>'updatePass'),
			
			array('sex, class_id, status_id, passwordAgain, passwordOld', 'safe'),
			
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, username, password, realname, tel, sex, class_id, status_id', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		    'class'=>array(self::BELONGS_TO, 'ClassInfo', 'class_id'),
				'status'=>array(self::BELONGS_TO, 'StatusType', 'status_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'username' => '用户名',
			'password' => '密码',
		  'passwordAgain' => '再次输入密码',
		  'passwordOld' => '老密码',
			'realname' => '真实姓名',
			'tel' => '电话',
			'sex' => '性别',
			'class_id' => '班级',
			'status_id' => '状态',
			'create_time' => '创建时间',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('realname',$this->realname,true);
		$criteria->compare('tel',$this->tel,true);
		$criteria->compare('sex',$this->sex,true);
		$criteria->compare('class_id',$this->class_id,true);
		$criteria->compare('status_id',$this->status_id);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * beforeSave method to do something commen
	 * @see CActiveRecord::beforeSave()
	 */
	public function beforeSave()
	{
	    if (parent::beforeSave()){
	    
	        if ($this->isNewRecord){
	            $this->create_time = $this->update_time = date('Y-m-d H:i:s');
	            $this->create_user_id = $this->update_user_id = Yii::app()->user->id;
	            $this->password = User::model()->encrypt($this->password); 
	        }else {
	            $this->update_time = date('Y-m-d H:i:s');
	            $this->update_user_id = Yii::app()->user->id;
	            if (!empty($this->passwordAgain))
	                $this->password=User::model()->encrypt($this->password);
	        }
	        
	        
	        return true;
	    }else{
	        return false;
	    }
	}
	
	
	/**
	 * Get Sex options from self defined const, then return it as an Array
	 * @return array $arrSexOptions[1]=>'男' ...
	 */
	public function getSexOptions()
	{
	    $arrSexOptions[self::SEX_MALE]='男';
	    $arrSexOptions[self::SEX_FEMALE]='女';
	    return $arrSexOptions;
	}
	
	/**
	 * get Sex Words through ID
	 * @param int $id
	 * @return string Sex Words like '男' ...
	 */
	public function getSexWord($id=1)
	{
	    $arrSex = $this->getSexOptions();
	    return isset($arrSex[$id]) ? $arrSex[$id] : '异常';
	}
	
	
	/**
	 * Validate Password
	 * @param string $password
	 * @return boolea true/false
	 */
	public function validatePassword($password)
	{
	    return $this->encrypt($password)===$this->password;
	}
	
	/**
	 * return md5 string of the input one.
	 * @param string $pass
	 */
	public function encrypt($pass)
	{
	    return md5($pass);
	}
}